package weaver.interfaces.jz.job;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.engine.jz.util.CommonUtil;
import com.engine.jz.util.KsUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.schedule.BaseCronJob;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2025/9/4
 * @Description 同步设备人员数据
 * @Author AdminZm
 */
public class SyncDeviceUserDataJob extends BaseCronJob {

    private String tb;

    private String ks;

    BaseBean baseBean = new BaseBean();

    @Override
    public void execute() {
        baseBean.writeLog("SyncDeviceUserDataJob start:" + tb + "、" + ks);
        RecordSet rs = new RecordSet();
        try {
            if (StringUtils.isNotEmpty(tb)) {
                baseBean.writeLog("SyncDeviceUserDataJob tb start.");
                try {
                    String sbip = rs.getPropValue("jzjg_zm_prop", "tb_ip");
                    List<String> snList = new ArrayList<>();
                    // 获取天波考勤设备ip
                    rs.execute("SELECT * FROM uf_kqsbdzgxgljmb WHERE sblx = 0 AND sbip is not null");
                    while (rs.next()) {
                        String id = rs.getString("id");
                        String sbxlh = rs.getString("sbxlh");
                        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(sbip) || StringUtils.isEmpty(sbxlh)) {
                            continue;
                        }
                        snList.add(sbxlh);
                    }
                    if (CollectionUtils.isEmpty(snList)) {
                        baseBean.writeLog("SyncDeviceUserDataJob tb snList is empty.");
                    } else {
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("SN", snList);
                        long taskId = System.currentTimeMillis();
                        paramMap.put("taskId", taskId);
                        paramMap.put("type", "queryRecords");
                        Map<String, Object> mapTemp = new HashMap<>();
                        mapTemp.put("photo", 0);
                        paramMap.put("Data", mapTemp);
                        baseBean.writeLog("SyncDeviceUserDataJob tb paramMap is:" + JSONObject.toJSONString(paramMap));
                        String url = "http://" + sbip + ":1820/Face/sendControl";
                        String result = HttpRequest.post(url)
                                .header(Header.CONTENT_TYPE, "application/json")
                                .body(JSONObject.toJSONString(paramMap))
                                .timeout(20000)
                                .execute().body();
                        baseBean.writeLog("SyncDeviceUserDataJob tb res:" + result);
                    }
                } catch (Exception e) {
                    baseBean.writeLog("SyncDeviceUserDataJob tb error:" + e);
                }
            }

            baseBean.writeLog("SyncDeviceUserDataJob ks start.");
            if (StringUtils.isNotEmpty(ks)) {
                // 获取考勤设备ip
                Map<String, String> ipMapKs = new HashMap<>();
                Map<String, String> sbwzMapKs = new HashMap<>();
                rs.execute("SELECT * FROM uf_kqsbdzgxgljmb WHERE sblx = 1 AND sbip is not null");
                while (rs.next()) {
                    String id = rs.getString("id");
                    String sbip = rs.getString("sbip");
                    String sblx = rs.getString("sblx");
                    String sbxlh = rs.getString("sbxlh");
                    String sbwz = rs.getString("sbwz");
                    if (StringUtils.isEmpty(id)) {
                        continue;
                    }
                    if (StringUtils.equals(sblx, "1") && StringUtils.isNotEmpty(sbip)) {
                        ipMapKs.put(id, sbip + "_" + sbxlh);
                        sbwzMapKs.put(id, sbwz);
                    }
                }
                if (CollectionUtils.isEmpty(ipMapKs)) {
                    baseBean.writeLog("SyncDeviceUserDataJob ip info is null.");
                    return;
                }

                // 获取工号与id对应
                Map<String, String> ghAndIdMap = new HashMap<>();
                Map<String, String> ghAndWkMap = new HashMap<>();
                rs.execute("SELECT id, loginid, workcode FROM hrmresource WHERE workcode is not null");
                while (rs.next()) {
                    String id = rs.getString("id");
                    String workcode = rs.getString("loginid");
                    String gh = rs.getString("workcode");
                    if (StringUtils.isEmpty(id) || StringUtils.isEmpty(workcode)) {
                        continue;
                    }
                    workcode = CommonUtil.removeLeadingZeros(workcode);
                    if (StringUtils.isEmpty(workcode)) {
                        continue;
                    }
                    ghAndIdMap.put(workcode, id);
                    ghAndWkMap.put(workcode, gh);
                }

                Gson gson = new Gson();
                Type type = new TypeToken<Map<String, Object>>() {
                }.getType();
                List<List> insertList = new ArrayList<>();
                SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");
                baseBean.writeLog("SyncDeviceUserDataJob start to get ks.");
                // 旷视
                if (!CollectionUtils.isEmpty(ipMapKs)) {
                    KsUtils ksUtils = new KsUtils();
                    Set<String> oldDataSet = new HashSet<>();
                    rs.execute("SELECT * FROM uf_kqjryjlb WHERE sblx = 0");
                    while (rs.next()) {
                        String rysbbh = rs.getString("rysbbh");
                        String szsbsn = rs.getString("szsbsn");
                        String ryxm = rs.getString("ryxm");
                        if (StringUtils.isEmpty(rysbbh) || StringUtils.isEmpty(szsbsn) || StringUtils.isEmpty(ryxm)) {
                            continue;
                        }
                        oldDataSet.add(szsbsn + "_" + rysbbh + "_" + ryxm);
                    }
                    for (Map.Entry<String, String> entry : ipMapKs.entrySet()) {
                        String sbip = null;
                        try {
                            String key = entry.getKey();
                            String sbwz = sbwzMapKs.get(key);
                            String value = entry.getValue();
                            sbip = value.split("_")[0];
                            String sn = value.split("_")[1];
                            // 登陆鉴权挑战
                            String paramStr = ksUtils.loginChallenge("admin", sbip);
                            Map<String, Object> mapC = gson.fromJson(paramStr, type);

                            Object session_id = mapC.get("session_id");
                            Object challenge = mapC.get("challenge");
                            Object salt = mapC.get("salt");
                            if (Objects.isNull(session_id) || Objects.isNull(challenge) || Objects.isNull(salt)) {
                                baseBean.writeLog("SyncDeviceUserDataJob login challenge failed.");
                                continue;
                            }
                            // 设备登陆
                            String loginRes = ksUtils.login(session_id.toString(), challenge.toString(), salt.toString(), sbip);
                            Map<String, Object> mapIn = gson.fromJson(loginRes, type);
                            Object sessionIdNew = mapIn.get("session_id");

                            Map<String, Object> paramMap = new HashMap<>();

                            int limit = 100;
                            int offset = 0;
                            paramMap.put("limit", limit);
                            paramMap.put("sort", "asc");
                            boolean isGoing = true;
                            while (isGoing) {
                                int offsetInt = offset * limit;
                                paramMap.put("offset", offsetInt);

                                String resultStr = HttpRequest.get("http://" + sbip + "/api/persons/query")
                                        .header(Header.CONTENT_TYPE, "application/json")
                                        .header(Header.COOKIE, "sessionID=" + sessionIdNew)
                                        .body(JSONObject.toJSONString(paramMap))
                                        .timeout(20000)
                                        .execute().body();

                                if (StringUtils.isEmpty(resultStr)) {
                                    isGoing = false;
                                    break;
                                }
                                Map<String, Object> hrmMap = gson.fromJson(resultStr, type);
                                Object paging = hrmMap.get("paging");
                                if (Objects.isNull(paging)) {
                                    isGoing = false;
                                    break;
                                }
                                Map<String, Object> pageMap = gson.fromJson(paging.toString(), type);
                                Object total = pageMap.get("total");
                                if (Objects.isNull(total)) {
                                    isGoing = false;
                                    break;
                                }
                                Object limitObj = pageMap.get("limit");
                                if (Objects.isNull(limitObj)) {
                                    isGoing = false;
                                    break;
                                }
                                if (new BigDecimal("100").compareTo(new BigDecimal(limitObj.toString())) == 0 && new BigDecimal(String.valueOf(offsetInt)).compareTo(new BigDecimal(total.toString())) < 0) {
                                    offset = offset + 1;
                                } else {
                                    isGoing = false;
                                }
                                Object data = hrmMap.get("data");
                                if (Objects.isNull(data)) {
                                    isGoing = false;
                                    break;
                                }

                                List<Map<String, String>> mapList = (List<Map<String, String>>) data;
                                for (Map<String, String> map : mapList) {
                                    String ygsbid = map.get("id");
                                    String name = map.get("person_name");
                                    String person_code = map.get("person_code");
                                    if (StringUtils.isEmpty(name) || StringUtils.isEmpty(ygsbid) || StringUtils.isEmpty(person_code)) {
                                        continue;
                                    }
                                    if ((!CollectionUtils.isEmpty(oldDataSet)) && oldDataSet.contains(sn + "_" + person_code + "_" + name)) {
                                        continue;
                                    }
                                    String loginidTemp = person_code;
                                    if (loginidTemp.length() == 4 && loginidTemp.startsWith("9")) {
                                        loginidTemp = "90" + loginidTemp;
                                    }
                                    String id = ghAndIdMap.get(loginidTemp);
                                    String gh = ghAndWkMap.get(loginidTemp);
                                    if (StringUtils.isEmpty(id)) {
                                        id = "0";
                                    }
                                    if (StringUtils.isEmpty(gh)) {
                                        gh = "0";
                                    }
                                    List list = new ArrayList();
                                    list.add(ygsbid);
                                    list.add(person_code);
                                    list.add(name);
                                    list.add(id);
                                    list.add(gh);
                                    list.add(sn);
                                    list.add("0");
                                    list.add("0");
                                    list.add(sbwz);
                                    list.add("146");
                                    list.add(UUID.randomUUID().toString());
                                    list.add("1");
                                    list.add("0");
                                    list.add(sdfDate.format(new Date()));
                                    list.add(sdfTime.format(new Date()));
                                    insertList.add(list);
                                }
                            }
                        } catch (Exception e) {
                            baseBean.writeLog("SyncDeviceUserDataJob ks single error:" + sbip + "、" + e);
                        }
                    }
                }
                if (!CollectionUtils.isEmpty(insertList)) {
                    baseBean.writeLog("SyncDeviceUserDataJob insertList size is:" + insertList.size());
                    String insertSql = "INSERT INTO uf_kqjryjlb (rysbid, rysbbh, ryxm, ygxm, yggh, szsbsn, sblx, sjlx, sbwz, " +
                            "formmodeid,MODEUUID,modedatacreater,modedatacreatertype, modedatacreatedate, modedatacreatetime) " +
                            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    rs.executeBatchSql(insertSql, insertList);
                }
            }
        } catch (Exception e) {
            baseBean.writeLog("SyncDeviceUserDataJob error:" + e);
        }
        baseBean.writeLog("SyncDeviceUserDataJob end.");
    }
}
